package com.miplus.ccrm.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miplus.ccrm.admin.controller.vo.*;
import com.miplus.ccrm.admin.mapper.SysGrpmgrMapper;
import com.miplus.ccrm.admin.pojo.SysGrp;
import com.miplus.ccrm.admin.pojo.SysGrpmgr;
import com.miplus.ccrm.admin.service.SysGrpService;
import com.miplus.ccrm.admin.mapper.SysGrpMapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author pc
* @description 针对表【sys_grp】的数据库操作Service实现
* @createDate 2024-03-01 14:16:59
*/
@Slf4j
@Service
public class SysGrpServiceImpl extends ServiceImpl<SysGrpMapper, SysGrp>
    implements SysGrpService{

    @Resource
    private SysGrpmgrMapper sysGrpmgrMapper;

    /**
     *
     * @param usrid
     * @param pid
     * @param gtype
     * @param uflag:是否返回用户信息。1：返回用户，其他没有用户。
     * @return
     */
    @Override
    public List<GrpTreeResVo> getGrpTree(String usrid,String pid,String gtype,String uflag)
    {
        List<GrpTreeResVo> all=null;
        if(JPubUtils.IsEmpty(usrid)){
            if(StringUtils.isNotEmpty(uflag) && "1".equals(uflag))
                all = getBaseMapper().getActiveGrpUser(pid,gtype);
            else
                all=getBaseMapper().getActiveGrp(pid,gtype);
        }else {
            all=getBaseMapper().grpTreeByUsrID(usrid);
        }
        List<GrpTreeResVo> tree = new ArrayList<>();
        if( all == null || all.size() == 0)
            return tree;
        for(GrpTreeResVo v : all )
        {
            if( StringUtils.isNotEmpty(v.getPid()) && !findGrpInList(v.getParentid(),all))
                v.setPid(null);
        }
        //获取到最外层的组信息
        List<GrpTreeResVo> parentGrp = all.stream().filter(dept -> JPubUtils.IsEmpty(dept.getPid())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(parentGrp)){
            for(GrpTreeResVo grp : parentGrp) {
                tree.add(grp);
                // 添加子节点
                addChildDept(grp, all);
            }
        }
        return tree;
    }
    private boolean findGrpInList(String grpid, List<GrpTreeResVo> all)
    {
        for(GrpTreeResVo v : all )
        {
            if( v.getId().equals(grpid))
                return true;
        }
        return false;
    }
    private void addChildDept(GrpTreeResVo sysGrp, List<GrpTreeResVo> all) {
        // 拿到所传部门的字部门列表
        if("user".equals(sysGrp.getGrouporuser()))
            return;
        log.info("addChildDept: grpid:{}", sysGrp.getId());
        List<GrpTreeResVo> tempList = all.stream()
                .filter(dept -> sysGrp.getId().equals(dept.getPid()))
                .collect(Collectors.toList());
        sysGrp.setChildren(tempList);
        if(tempList != null){
            log.info("addChildDept:{}, child cnt:{}",sysGrp.getId(), tempList.size());
        }
        tempList.forEach(dept -> {
            //添加子节点
            addChildDept(dept, all);
        });
    }

    @Override
    public List<GrpIDResVo> userMgrList(String usrid)
    {
        log.info("userMgrList:{}",usrid);
        return getBaseMapper().userMgrList(usrid);
    }

    @Override
    public CmdResVo updateGrpStatus(String usrid, GrpReqVo paras)
    {
        SysGrp grp=new SysGrp();
        grp.setGrpid(paras.getGrpid());
        grp.setStatus(paras.getStatus());
        grp.setMdusr(usrid);
        grp.setMddt(new Date());
        int ret=baseMapper.updateById(grp);
        if(ret>0&&JPubUtils.IsEqual(paras.getStatus(),"1")){
            baseMapper.update(grp,
                    new QueryWrapper<SysGrp>().eq("parentid",paras.getGrpid())
                    );
        }

        return new CmdResVo(ret);
    }

    @Override
    public CmdResVo deleteGrp(String usrid, GrpReqVo paras)
    {
        log.info("deleteGrp({}):{}",usrid,paras.getGrpid());
        sysGrpmgrMapper.delete(
                new QueryWrapper<SysGrpmgr>().eq("grpid",paras.getGrpid())
        );
        int ret=baseMapper.deleteById(paras.getGrpid());

        return new CmdResVo(ret);
    }

    @Override
    public CmdResVo updateGrp(String usrid, GrpEditReqVo paras)
    {
        SysGrp grp=new SysGrp();
        grp.setGrpid(paras.getId());
        grp.setStatus(paras.getStatus());
        grp.setGrpname(paras.getName());
        grp.setType(paras.getTypeid());
        grp.setParentid(paras.getPid());
        grp.setGrplevel(paras.getGrplevel());
        grp.setMdusr(usrid);
        grp.setMddt(new Date());
        int ret=baseMapper.updateById(grp);
        return new CmdResVo(ret);
    }

    @Override
    public CmdResVo insertGrp(String usrid, GrpEditReqVo paras)
    {
        SysGrp grp=baseMapper.selectById(paras.getId());
        if(grp!=null){//2024-05-31
            log.info("insertGrp({}):HasExist",paras.getId());
            throw new ServiceException(EnumRCode.HasExist.value, EnumRCode.HasExist.name);
        }
        grp=new SysGrp();
        grp.setGrpid(paras.getId());
        grp.setStatus(paras.getStatus());
        grp.setGrpname(paras.getName());
        grp.setType(paras.getTypeid());
        grp.setParentid(paras.getPid());
        grp.setGrplevel(paras.getGrplevel());
        grp.setCrusr(usrid);
        grp.setCrdt(new Date());
        grp.setMdusr(usrid);
        grp.setMddt(new Date());
        int ret=baseMapper.insert(grp);
        return new CmdResVo(ret);
    }

    @Override
    public List<NamesResVo> getPermGrpList(String $usrid,String gtype)
    {
        return baseMapper.getPermGrpList($usrid,gtype);
    }

    @Override
    public List<NamesResVo> getActiveGrpList(String gtype)
    {
        return baseMapper.getActiveGrpList(gtype);
    }
}




